package com.dashan.process;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.dashan.register.ServiceRegister;

/**
 * 以bio方式对外提供服务
 * @author b5m
 *
 */
public class Server01 {
	
	private static final ExecutorService EXECUTOR = Executors.newFixedThreadPool(3);
	
	
	public static void main(String[] args) throws Exception {
		
		@SuppressWarnings("resource")
		ServerSocket ss = new ServerSocket(8888);
		while(true) {
			Socket socket = ss.accept();
			EXECUTOR.execute(new Process(socket));
		}
	}
	
	
	/**
	 * 每个请求对开启一个线程去处理
	 * @author b5m
	 *
	 */
	static class Process implements Runnable {
		
		private Socket socket;
		
		public Process(Socket socket) {
			this.socket = socket;
		}
		
		@Override
		public void run() {
			try {
				System.out.println(Thread.currentThread().getName()+" processing...");
				InputStream inputStream = socket.getInputStream();
				ObjectInputStream ois = new ObjectInputStream(inputStream);
				//取出请求参数
				String className = ois.readUTF();
				String methodName = ois.readUTF();
				@SuppressWarnings("rawtypes")
				Class[] clazz = (Class[])ois.readObject();
				Object[] params = (Object[])ois.readObject();
				Object serviceByName = ServiceRegister.getServiceByName(className);
				//调用目标方法
				Method method = serviceByName.getClass().getMethod(methodName, clazz);
				Object result = method.invoke(serviceByName, params);
				
				//响应
				OutputStream outputStream = socket.getOutputStream();
				ObjectOutputStream oos = new ObjectOutputStream(outputStream);
				oos.writeObject(result);
				
				if(oos != null) {
					oos.close();
				}
				
				if(ois != null) {
					ois.close();
				}
				
				if(outputStream != null) {
					outputStream.close();
				}
				
				if(inputStream != null) {
					inputStream.close();
				}
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
